<?php

/**
 * This is the model class for table "admin".
 *
 * The followings are the available columns in table 'admin':
 * @property integer $id
 * @property string $first_name
 * @property string $last_name
 * @property string $login
 * @property string $password
 * @property string $mail
 */
class Admin extends CActiveRecord
{
    private $_identity;

	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	public function tableName()
	{
		return 'admin';
	}

    public function getDbConnection()
    {
        if ($this->isLive())
            return Yii::app()->live;
        else
            return Yii::app()->db;
    }

    private function isLive()
    {
        return $_SERVER['HTTP_HOST'] == 'valerchyck.hol.es';
    }

	public function rules()
	{
		return array(
			array('first_name, last_name, login, password, mail', 'required'),
			array('first_name, last_name, login, password', 'length', 'max'=>50),
			array('mail', 'length', 'max'=>100),
			array('id, first_name, last_name, login, password, mail', 'safe', 'on'=>'search'),
		);
	}

	public function attributeLabels()
	{
		return array(
			'id' => 'Ид',
			'first_name' => 'Имя',
			'last_name' => 'Фамилия',
			'login' => 'Логин',
			'password' => 'Пароль',
			'mail' => 'E-Mail',
		);
	}

    public function login()
    {
        if($this->_identity===null)
        {
            $this->_identity = new UserIdentity($this->login, $this->password);
            $this->_identity->authenticate();
        }
        if($this->_identity->errorCode === UserIdentity::ERROR_NONE)
        {
            Yii::app()->user->login($this->_identity);
            return true;
        }
        else{
            return false;
        }
    }

    public function validatePassword($password)
    {
        return $this->password == md5($password);
    }

	public function search()
	{
		$criteria = new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('first_name',$this->first_name,true);
		$criteria->compare('last_name',$this->last_name,true);
		$criteria->compare('login',$this->login,true);
		$criteria->compare('password',$this->password,true);
		$criteria->compare('mail',$this->mail,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
}